package com.hk.commons.utils.yingmi;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.message.BasicNameValuePair;

import com.hk.commons.AES;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HuochaiApiUtils {
	private static Logger logger = LoggerFactory.getLogger(HuochaiApiUtils.class);

	private static TrustManager myX509TrustManager = new X509TrustManager() {

		@Override
		public void checkClientTrusted(
				java.security.cert.X509Certificate[] chain, String authType)
				throws CertificateException {

		}

		@Override
		public void checkServerTrusted(
				java.security.cert.X509Certificate[] chain, String authType)
				throws CertificateException {

		}

		@Override
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {

			return null;
		}
	};
	
	public static String doPost(String updUrl, Long orderId){
		String result = null; 

		
		//设置请求参数
		String jsonStr = "{\"orderId\":\"" + orderId.toString() + "\"}";
		String info = AES.encrypt(jsonStr);
		BasicNameValuePair parm = new BasicNameValuePair("orderInfo", info);
		 
		
		SSLContext sslcontext;
		try {
			sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);
			
			URL requestUrl = new URL(updUrl+"?" + parm);  
			HttpsURLConnection httpsConn = (HttpsURLConnection)requestUrl.openConnection();
			
			//设置套接工厂 
			httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
			
			 //加入数据 
		    httpsConn.setRequestMethod("POST"); 
		    httpsConn.setDoOutput(true); 
		    DataOutputStream out = new DataOutputStream( 
		            httpsConn.getOutputStream()); 
		    
		    out.flush(); 
		    out.close();

		    //获取输入流 
		    BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream())); 
		    int code = httpsConn.getResponseCode(); 
		    if (HttpsURLConnection.HTTP_OK == code){ 
		        String temp = in.readLine(); 
		        /*连接成一个字符串*/ 
		        while (temp != null) { 
		            if (result != null) 
		                result += temp; 
		            else 
		                result = temp; 
		            temp = in.readLine(); 
		        } 
		    }
			in.close();
			
		} catch (Exception e) {
			logger.error("huochai api do post has something wrong. ", e.getMessage());
		}

	    return result;
	}
}
